package service

import (
	"context"
	"github.com/gogf/gf/crypto/gmd5"
	"myGo/app/dao"
	"myGo/app/model"
	"myGo/library/common"
)

var User = userService{}

type userService struct{}

func (user *userService) GetList(ctx context.Context) (interface{}, error) {
	res, err := dao.User.Ctx(ctx).All()
	return res, err
}

func (user *userService) Create(ctx context.Context, data *model.UserServiceSignUpReq) error {
	data.Salt = common.RandStringBytes(6)
	common.BenchmarkAddStringWithBuffer(&data.Password, data.Password, data.Salt)
	data.Password, _ = gmd5.EncryptString(data.Password)

	if _, err := dao.User.Ctx(ctx).
		Data(data).Fields("passport,password,nickname,salt").
		Insert(); err != nil {
		return err
	}
	return nil
}

func (user *userService) Update(ctx context.Context, data *model.UserServiceUpdateReq) error {
	if _, err := dao.User.Ctx(ctx).
		Where("id", 2).
		Data(data).Fields("passport,nickname").
		Update(); err != nil {
		return err
	}
	return nil
}

func (user *userService) Info(ctx context.Context, id int) (interface{}, error) {
	var modelUser model.User
	err := dao.User.Ctx(ctx).Where("id", id).Scan(&modelUser)
	if err != nil {
		return nil, err
	} else {
		return modelUser, nil
	}
}

func (user *userService) Delete(ctx context.Context, id int) error {
	_, err := dao.User.Ctx(ctx).Where("id", id).Delete()
	if err != nil {
		return err
	} else {
		return nil
	}
}
